package net.goutalk.glcs.module.organization.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import net.goutalk.glcs.common.page.ConventPage;
import net.goutalk.glcs.common.page.PageOutput;
import net.goutalk.glcs.common.utils.VoToColumnUtil;
import net.goutalk.glcs.module.organization.dto.WeChatDepartPageDto;
import net.goutalk.glcs.module.organization.entity.Department;
import net.goutalk.glcs.module.organization.mapper.DepartmentMapper;
import net.goutalk.glcs.module.organization.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.goutalk.glcs.module.organization.vo.DepartmentTreeVo;
import net.goutalk.glcs.module.organization.vo.WeChatDepartPageVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 机构 服务实现类
 * </p>
 *
 * @author tanyujie
 * @since 2022-03-02
 */
@Service
@AllArgsConstructor
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    private final DepartmentMapper departmentMapper;
    @Override
    public Object Ipage(WeChatDepartPageDto dto) {
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(dto.getKeyword()),Department::getName,dto.getKeyword())
                .select(Department.class,x -> VoToColumnUtil.fieldsToColumns(WeChatDepartPageVO.class).contains(x.getProperty()));
        IPage<Department> page = departmentMapper.selectPage(ConventPage.getPage(dto), queryWrapper);
        List<Department> records = page.getRecords();
        for (Department record : records) {
            record.setRemark("部门更新成功");
            record.setSortCode(1);
        }
        PageOutput<WeChatDepartPageVO> pageOutput = ConventPage.getPageOutput(page, WeChatDepartPageVO.class);
        return pageOutput;
    }

    /**
     * 获取所有的子集id
     * @param deptIds
     * @param voList
     * @return
     */
    @Override
    public List<Long> getAllChildIds(List<Long> deptIds, List<DepartmentTreeVo> voList) {
        List<Long> ids = new ArrayList<>();
        for (Long deptId : deptIds) {
            if (voList.stream().anyMatch(x -> x.getParentId().equals(deptId))){
                List<DepartmentTreeVo> child = voList.stream().filter(x -> x.getParentId().equals(deptId)).collect(Collectors.toList());
                List<Long> allChildId = child.stream().map(DepartmentTreeVo::getId).collect(Collectors.toList());
                List<Long> allChildId1= getAllChildIds(allChildId, voList);
                ids.addAll(allChildId);
                ids.addAll(allChildId1);
            }
        }
        return ids;
    }
}
